package com.codeing.demo.redis.redission.service;

import com.codeing.demo.redis.redission.entities.Content;
import com.codeing.demo.utils.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**直播弹幕
 * @auther zzyy
 * @create 2021-05-23 16:11
 */
@Service
@Slf4j
public class LiveTaskService
{

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     *模拟直播间的数据
     */
    @PostConstruct
    public void init(){
        log.info("启动初始化,淘宝直播弹幕case开始 ..........");

        new Thread(() -> {
            AtomicInteger atomicInteger = new AtomicInteger();
            //模拟5秒一批数据
            while (true)
            {
                if(atomicInteger.get() == 6){
                    break;
                }
                //模拟直播100房间号 的弹幕数据
                String  key= Constants.ROOM_KEY+100;
                Random rand = new Random();

                for(int i=1;i<=5;i++){
                    Content content = new Content();

                    int id= rand.nextInt(1000);
                    content.setUserId(id);

                    int temp= rand.nextInt(100);
                    content.setContent("发表"+temp);

                    long time=System.currentTimeMillis()/1000;
                    //对应的redis命令 zadd room:100 time content
                    this.redisTemplate.opsForZSet().add(key,content,time);

                    log.debug("模拟直播间100房间号的发言弹幕数据={}",content);
                }
                //TODO 在分布式系统中，建议用xxl-job来实现定时,此处简单模拟
                try { TimeUnit.SECONDS.sleep(5); } catch (InterruptedException e) { e.printStackTrace(); }
                atomicInteger.getAndIncrement();
            }
        },"init_Live_Data").start();
    }

}

